<template>
  <div class="show-all" style="width: 1500px">
    <el-card>
      <div class="header">
        <span>新增销售单</span>
        <span class="required-tip">* 为必填项</span>
      </div>
        <el-form
        ref="ruleFormRef"
        style="max-width: 1500px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        >
        <el-row :gutter="20">
          <el-col :span="8">
<el-form-item label="销售单号" prop="sell__Number">
<el-input v-model="ruleForm.sell__Number" />
</el-form-item>
          </el-col>
          <el-col :span="8">
<el-form-item label="单据类型" prop="sell__Types">
<el-select v-model="ruleForm.sell__Types" placeholder="请选择销售类别">
<el-option label="销售中" value="销售中" />
<el-option label="全部销售" value="全部销售" />
<el-option label="部分销售" value="部分销售" />
</el-select>
</el-form-item>
          </el-col>
          <el-col :span="8">
<el-form-item label="关联订单号" prop="sellOrder__Number">
<el-input v-model="ruleForm.sellOrder__Number" />
</el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
<el-form-item label="客户名称" prop="customer_Name">
<el-input v-model="ruleForm.customer_Name" />
</el-form-item>
          </el-col>
          <el-col :span="8">
<el-form-item label="联系人" prop="sell__Name">
<el-input v-model="ruleForm.sell__Name" />
</el-form-item>
          </el-col>
          <el-col :span="8">
<el-form-item label="客户编号" prop="customer__Number">
<el-input v-model="ruleForm.customer__Number" />
</el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
<el-form-item label="手机号" prop="sell__Phone">
<el-input v-model="ruleForm.sell__Phone" />
</el-form-item>
          </el-col>
          <el-col :span="8">
<el-form-item label="收货日" required>
<el-col :span="11">
<el-form-item prop="sell__Day">
<el-date-picker
v-model="ruleForm.sell__Day"
type="date"
aria-label=""
placeholder=""
style="width: 100%"
/>
</el-form-item>
</el-col>
</el-form-item>
          </el-col>
          <el-col :span="8">
<el-form-item label="备注" prop="sell__Desc">
<el-input v-model="ruleForm.sell__Desc" type="textarea" />
</el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
<el-form-item label="制单人" prop="sell__Preparer">
<el-input v-model="ruleForm.sell__Preparer" />
</el-form-item>
          </el-col>
          <el-col :span="8">
<el-form-item label="制单时间" prop="sell__Time">
<el-input v-model="ruleForm.sell__Time" readonly />
</el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>

<div class="flex flex-wrap gap-4">
    <h2>产品信息</h2>
    <el-button type="success" plain @click="dialogTableVisible = true">+新增产品</el-button>
    
    <!-- 显示选中的产品信息 -->
    <div v-if="selectedProducts.length > 0" style="margin: 10px 0; padding: 10px; background-color: #f0f9ff; border-radius: 4px; border: 1px solid #b3d8ff;">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
        <h4 style="margin: 0; color: #409eff;">已选中的产品 ({{ selectedProducts.length }}个):</h4>
        <div style="display: flex; align-items: center; gap: 10px;">
          <span style="color: #67c23a; font-weight: bold;">选中产品总价: ¥{{ calculateSelectedTotal() }}</span>
          <el-button type="danger" size="small" @click="batchDeleteSelected">批量删除</el-button>
        </div>
      </div>
      <div style="display: flex; flex-wrap: wrap; gap: 10px;">
        <el-tag 
          v-for="product in selectedProducts" 
          :key="product.product_ID"
          type="info"
          closable
          @close="removeSelectedProduct(product.product_ID)"
        >
          {{ product.product_Name }} (ID: {{ product.product_ID }})
        </el-tag>
      </div>
    </div>
    
    <el-card style="width: 1500px" shadow="always">
      <el-table 
        ref="mainTableRef"
        :data="tableData" 
        :model="ruleForm" 
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
      <el-table-column prop="product_Name" label="产品名称" width="180" />
      <el-table-column prop="product_Number" label="产品编码" width="180" />
      <el-table-column prop="specifications" label="规格" width="180" />
      <el-table-column prop="unit_Name" label="单位" width="180" />
      <el-table-column prop="price" label="单价" width="180" />
      <el-table-column prop="sProduct__Num" label="数量" width="180" >
        <template v-slot="scoped">
          <el-input 
            v-model="scoped.row.sProduct__Num" 
            style="width: 120px;" 
            type="number"
            min="0"
            @input="calculateTotalPrice(scoped.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="总价" width="180">
        <template v-slot="scoped">
          {{ calculateRowTotal(scoped.row) }}
        </template>
      </el-table-column>
      <el-table-column  label="操作" >
        <template v-slot="scoped">
          <el-button type="danger" @click="deleteRow(scoped.$index)">删除</el-button>
        </template>
      </el-table-column>
      </el-table>
      
      <!-- 总计显示 -->
      <div style="text-align: right; margin-top: 15px; font-size: 16px; font-weight: bold; color: #409EFF;">
        总计: ¥{{ calculateGrandTotal() }}
      </div>
    </el-card>
</div>

<!-- 采购新增信息弹出框 -->
 <el-dialog v-model="dialogTableVisible" title="选择产品" width="1000" draggable>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="产品编号">
      <el-input v-model="data1.Product_Number" placeholder="请输入编码" clearable />
    </el-form-item>

    <el-form-item label="产品名称">
      <el-input v-model="data1.Product_Name" placeholder="请输入名称" clearable />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="Productshow1()">搜索</el-button>
    </el-form-item>
    </el-form>

    <!-- 弹出框新增产品信息的显示 -->
    <el-table 
      ref="dialogTableRef"
      :data="gridData" 
      style="width: 1200;"
      @selection-change="handleDialogSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column property="product_Number" label="产品编码" width="100" />
      <el-table-column property="product_Name" label="产品名称" width="100" />
      <el-table-column property="specifications" label="规格" width="100" />
      <el-table-column property="category_Name" label="类别" width="100" />
      <el-table-column property="unit_Name" label="存储单位" width="100" />
      <el-table-column property="packaging_Type" label="包装类型" width="100" />
      <el-table-column property="price" label="单价" width="100" />
      <el-table-column property="weight" label="重量" width="100" />
  
    </el-table>
     <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogTableVisible = false">关闭</el-button>
        <el-button type="primary" @click="addSelectedProducts">选择</el-button>
      </div>
    </template>

    <!-- 分页数据的显示 -->
    <el-pagination
    v-model:current-page="data1.PageIndex"
    v-model:page-size="data1.PageSize"
    :page-sizes="[15, 20, 25, 30]"
    layout="total, sizes, prev, pager, next, jumper"
    prev-text="上一页"
    next-text="下一页"
    :total="data1.totaCount"
    />
  </el-dialog>


  <!-- 采购信息的点击/取消按钮 -->
<el-form-item style="margin-left: 600px;margin-top: 20px;width: 200px;">
<el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
<el-button @click="resetForm(ruleFormRef)">取消</el-button>
</el-form-item>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { BusinessWrite } from '@/http/axiosHelper'
import { BasicsRed } from '@/http/axiosHelper'  //段
import { useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
// 移除未使用的RuleForm接口
// interface RuleForm {
//   name: string
//   region: string
//   count: string
//   date1: string
//   date2: string
//   delivery: boolean
//   location: string
//   type: string[]
//   resource: string
//   desc: string
// }



//单号的唯一
// 改进版 - 添加持久化支持
const generateDateBasedNumber = (incrementLength: number = 4) => {
  const now = new Date();
  const datePart = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`;
  
  // 从localStorage读取或初始化计数器
  const storageKey = `dateNumCounter_${datePart}`;
  let currentCount = localStorage.getItem(storageKey);
  
  // 如果localStorage中没有值，则初始化为0
  if (currentCount === null) {
    currentCount = '0';
  }
  
  // 转换为数字，递增，然后转回字符串
  const numericCount = parseInt(currentCount, 10) + 1;
  currentCount = numericCount.toString();
  
  // 保存新的计数器值
  localStorage.setItem(storageKey, currentCount);

  // 确保incrementLength是数字，然后生成递增部分
  const incrementPart = currentCount.padStart(incrementLength, '0');
  
  return datePart + incrementPart;
};

const ruleFormRef = ref<FormInstance>()
// 添加表格引用
const mainTableRef = ref<any>()
const dialogTableRef = ref<any>()
// 添加路由
const router = useRouter()

// 存储选中的数据
const selectedProducts = ref<any[]>([])
const dialogSelectedProducts = ref<any[]>([])

const ruleForm = reactive<{
  sell__Number: string
  sell__Types: string
  sellOrder__Number: string
  customer__Number: string
  customer_Name: string
  sell__Name: string
  sell__Phone: string
  sell__Day: string
  sell__Desc: string
  sell__Preparer: string
  sell__Time: string
  sProduct__Num: string
  product_ID: number
  sRefund_Num: string
  state: number
  receivable_Id: number
  warehouse_Id: number
  createUse: string
  upDateUse: string
  createTime: string
  upDataTime: string
  isDeleted: boolean
  sell_State: number
  sell_Return: boolean
  return_Number: string
}>({
  "sell__Number": generateDateBasedNumber(),
  "sell__Types": "",
  "sellOrder__Number": "",
  "customer__Number": "",
  "customer_Name": "",
  "sell__Name": "",
  "sell__Phone": "",
  "sell__Day": "",
  "sell__Desc": "",
  "sell__Preparer": "",
  "sell__Time": new Date().toISOString(),
  "sProduct__Num": "",
  "product_ID": 0,
  "sRefund_Num": "",
  "state": 0,
  "receivable_Id": 0,
  "warehouse_Id": 0,
  "createUse": "",
  "upDateUse": "",
  "createTime": new Date().toISOString(),
  "upDataTime": new Date().toISOString(),
  "isDeleted": false,
  "sell_State": 0,
  "sell_Return": false,
  "return_Number": ""
})

//表单验证
const rules = reactive<FormRules>({
  sell__Types: [
    { required: true, message: '请选择单据类型', trigger: 'blur' },
  ],
  customer_Name: [
    { required: true, message: '请输入客户名称', trigger: 'blur' },
  ],
  sell__Name: [
    { required: true, message: '请输入联系人', trigger: 'blur' },
  ],
})

//单击保存事件
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  
  // 检查是否有产品数据
  if (tableData.value.length === 0) {
    ElMessage.error('请先添加产品信息');
    return;
  }

  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        // 处理日期格式
        let formData = { ...ruleForm };
        if (formData.sell__Day) {
          formData.sell__Day = new Date(formData.sell__Day).toISOString();
        }
        
        // 为每个产品创建一个销售记录
        const submitPromises = tableData.value.map(async (product: any) => {
          const sellData = {
            ...formData,
            product_ID: product.product_ID,
            sProduct__Num: product.sProduct__Num ? product.sProduct__Num.toString() : "1",
            createUse: formData.sell__Preparer || "系统用户",
            upDateUse: formData.sell__Preparer || "系统用户",
            createTime: new Date().toISOString(),
            upDataTime: new Date().toISOString(),
            isDeleted: false,
            sell_State: 0,
            sell_Return: false,
            state: 0,
            receivable_Id: 0,
            warehouse_Id: 0,
            sRefund_Num: "",
            return_Number: ""
          };

          console.log('提交的销售数据:', sellData);

          return BusinessWrite.post('api/Purchase/AddSell', sellData);
        });

        // 等待所有产品提交完成
        const results = await Promise.all(submitPromises);
        
        // 检查是否所有请求都成功
        const allSuccess = results.every((res: any) => res.data.code === 200 || res.status === 200);
        
        if (allSuccess) {
          ElMessage.success('销售单提交成功！');
          
          // 询问用户是否要跳转到销售单列表
          ElMessageBox.confirm(
            '销售单已成功提交！是否跳转到销售单列表查看？',
            '提交成功',
            {
              confirmButtonText: '查看列表',
              cancelButtonText: '继续新增',
              type: 'success',
            }
          )
          .then(() => {
            // 跳转到销售单列表页面
            router.push({ name: 'SellShow' });
          })
          .catch(() => {
            // 用户选择继续新增，重置表单
            // 重置表单和数据
            formEl.resetFields();
            tableData.value = [];
            selectedProducts.value = [];
            
            // 重新生成单号
            ruleForm.sell__Number = generateDateBasedNumber();
            ruleForm.sell__Time = new Date().toISOString();
            ruleForm.createTime = new Date().toISOString();
            ruleForm.upDataTime = new Date().toISOString();
            
            ElMessage.info('可以继续新增销售单');
          });
          
        } else {
          ElMessage.error('部分数据提交失败，请检查后重试');
        }
        
      } catch (error: any) {
        console.error('提交失败:', error);
        ElMessage.error('提交失败: ' + (error.response?.data?.message || error.message || '未知错误'));
      }
    } else {
      console.log('表单验证失败:', fields);
      ElMessage.error('请填写必填项');
    }
  })
}

//信息的重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  
  ElMessageBox.confirm(
    '确定要重置表单吗？这将清空所有已填写的数据和产品信息。',
    '确认重置',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    // 重置表单
    formEl.resetFields();
    
    // 清空产品数据
    tableData.value = [];
    selectedProducts.value = [];
    
    // 重新生成单号和时间
    ruleForm.sell__Number = generateDateBasedNumber();
    ruleForm.sell__Time = new Date().toISOString();
    ruleForm.createTime = new Date().toISOString();
    ruleForm.upDataTime = new Date().toISOString();
    
    ElMessage.success('表单已重置');
  })
  .catch(() => {
    ElMessage.info('已取消重置');
  });
}





//生命周期钩子函数
onMounted(()=>{
Productshow()
Productshow1()
})



//数据信息的显示
const data = ref<{
    PageIndex: number
    PageSize: number
    totaCount: number
    Purchase_Number: string
    Product_Number: string
    Product_Name: string
    Category_ID: string
}>({
    PageIndex : 1,
    PageSize : 15,
    totaCount:0,
    Purchase_Number:'',
    Product_Number:'',
    Product_Name:'',
    Category_ID:''
})
const tableData = ref<any[]>([])
// 处理主表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedProducts.value = selection;
  console.log('主表格选中的产品:', selectedProducts.value);
}

// 处理弹出框表格选择变化
const handleDialogSelectionChange = (selection: any[]) => {
  dialogSelectedProducts.value = selection;
  console.log('弹出框选中的产品:', dialogSelectedProducts.value);
}

const Productshow = () =>{
  BasicsRed.get('api/Product/GetProductHandle',{
    params:{
      PageIndex:data.value.PageIndex,
      PageSize:data.value.PageSize
    }
  })
  .then((res: any) => {
  tableData.value = res.data.data;
  data.value.totaCount = res.data.totaCount
  })
  .catch((err: any) => {
    console.error('获取产品信息失败:', err)
  })
}


//新增弹出框
const dialogTableVisible = ref(false)
// 移除未使用的变量
// const dialogFormVisible = ref(false)
// const formLabelWidth = '140px'

//新增弹出框产品信息显示
const gridData = ref<any[]>([])
const data1 = ref<{
    PageIndex: number
    PageSize: number
    totaCount: number
    Purchase_Number: string
    Product_Number: string
    Product_Name: string
    Category_ID: string
}>({
    PageIndex : 1,
    PageSize : 15,
    totaCount:0,
    Purchase_Number:'',
    Product_Number:'',
    Product_Name:'',
    Category_ID:''
})
const Productshow1 = () =>{
  BasicsRed.get('/api/Product/GetProductHandle',{
    params:{
      PageIndex:data1.value.PageIndex,
      PageSize:data1.value.PageSize,
      Product_Number: data1.value.Product_Number,
      Product_Name: data1.value.Product_Name,
    }
  })
  .then((res: any) => {
  gridData.value = res.data.data;
  data1.value.totaCount = res.data.totalCount
  })
  .catch((err: any) => {
    console.error('获取产品信息失败:', err)
  })
}




//新增信息搜索
const formInline = reactive<{
  product_Number: string
  product_Name: string
}>({
  product_Number: '',
  product_Name: '',
})

// 计算单行总价
const calculateRowTotal = (row: any) => {
  const price = parseFloat(row.price?.toString() || '0') || 0;
  const quantity = parseFloat(row.sProduct__Num?.toString() || '0') || 0;
  const total = price * quantity;
  return total.toFixed(2);
}

// 计算总价并更新表格数据
const calculateTotalPrice = (row: any) => {
  if (row.sProduct__Num) {
    // 确保数量不为负数且为有效数字
    const num = parseFloat(row.sProduct__Num.toString());
    if (isNaN(num) || num < 0) {
      row.sProduct__Num = 1;
      ElMessage.warning('数量必须为大于0的数字');
    } else {
      row.sProduct__Num = num;
    }
  } else {
    row.sProduct__Num = 1;
  }
  // 触发表格重新渲染
  tableData.value = [...tableData.value];
}

// 计算所有行的总价
const calculateGrandTotal = () => {
  let grandTotal = 0;
  tableData.value.forEach((row: any) => {
    const price = parseFloat(row.price?.toString() || '0') || 0;
    const quantity = parseFloat(row.sProduct__Num?.toString() || '0') || 0;
    grandTotal += price * quantity;
  });
  return grandTotal.toFixed(2);
}

// 删除行功能 - 只删除列表数据，不删除数据库数据
const deleteRow = (index: number) => {
  ElMessageBox.confirm(
    '确定要删除这条产品信息吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 从数组中移除指定索引的行
      tableData.value.splice(index, 1);
      ElMessage.success('删除成功')
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 选择产品功能
const addSelectedProducts = () => {
  if (dialogSelectedProducts.value.length === 0) {
    ElMessage.warning('请先选择产品');
    return;
  }

  let addedCount = 0;
  let existingCount = 0;

  // 将选中的产品添加到主表格
  dialogSelectedProducts.value.forEach((product: any) => {
    // 检查产品是否已经存在
    const existingProduct = tableData.value.find((item: any) => item.product_ID === product.product_ID);
    if (!existingProduct) {
      // 添加产品到表格，设置默认数量为1
      const newProduct = {
        ...product,
        sProduct__Num: 1
      };
      tableData.value.push(newProduct);
      addedCount++;
    } else {
      existingCount++;
    }
  });

  // 清空弹出框选择
  (dialogTableRef.value as any)?.clearSelection();
  dialogSelectedProducts.value = [];
  
  // 关闭弹出框
  dialogTableVisible.value = false;
  
  // 显示添加结果
  if (addedCount > 0) {
    ElMessage.success(`成功添加 ${addedCount} 个产品${existingCount > 0 ? `，${existingCount} 个产品已存在` : ''}`);
  } else if (existingCount > 0) {
    ElMessage.warning(`所选产品均已存在`);
  }
}

// 获取选中的产品ID列表
const getSelectedProductIds = () => {
  return selectedProducts.value.map((product: any) => product.product_ID);
}

// 移除选中的产品
const removeSelectedProduct = (productId: number) => {
  const index = selectedProducts.value.findIndex((product: any) => product.product_ID === productId);
  if (index !== -1) {
    selectedProducts.value.splice(index, 1);
    ElMessage.success(`产品已移除`);
  }
};

// 批量删除选中的产品
const batchDeleteSelected = () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请先选择要删除的产品');
    return;
  }

  ElMessageBox.confirm(
    `确定要批量删除选中的 ${selectedProducts.value.length} 个产品吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 获取选中产品的ID列表
      const selectedIds = selectedProducts.value.map((product: any) => product.product_ID);
      
      // 从主表格中删除选中的产品
      tableData.value = tableData.value.filter((item: any) => !selectedIds.includes(item.product_ID));
      
      // 清空选中状态
      selectedProducts.value = [];
      (mainTableRef.value as any)?.clearSelection();
      
      ElMessage.success('批量删除成功');
    })
    .catch(() => {
      ElMessage.info('已取消批量删除');
    });
};

// 计算选中产品的总价
const calculateSelectedTotal = () => {
  let total = 0;
  selectedProducts.value.forEach((product: any) => {
    const price = parseFloat(product.price?.toString() || '0') || 0;
    const quantity = parseFloat(product.sProduct__Num?.toString() || '0') || 0;
    total += price * quantity;
  });
  return total.toFixed(2);
};












</script>

<style scoped>
.show-all {
  padding: 24px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}
.required-tip {
  color: #f56c6c;
  font-size: 14px;
}
.purchase-form {
  max-width: 1200px;
}
</style>
